package com.zhang.web.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;


@WebFilter("/*")
public class ACharacterFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }
    @Override
    public void destroy() {

    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse rep, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("A.乱码过滤器");

        //将父接口转为子接口
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) rep;
        //解决请求响应乱码
        setUTF(request,response);

        filterChain.doFilter(request,response);

    }



    //解决请求响应乱码
    public void setUTF(HttpServletRequest request, HttpServletResponse response){
        //获取请求方法
        String method = request.getMethod();

        //(1)解决post请求乱码
        if(method.equalsIgnoreCase("post")){
            try {
                request.setCharacterEncoding("utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        //(2)处理响应乱码
        response.setContentType("text/html;charset=utf-8");
    }


}
